<template>
  <div class="step-two">
    <!-- 导入文件 -->
    <div v-if="!readonly" class="section import-file-section">
      <FileUpload
        ref="fileUpload"
        title="导入文件"
        :template-name="'负荷导入模板.xls'"
        :upload-api="uploadApiFunction"
        @parse-success="handleParseSuccess"
        @reset="handleUploadReset"
        @download="handleDownloadTemplate"
      />
    </div>

    <!-- 数据表格 -->
    <div class="section data-table-section" v-if="loadDetailsList.length > 0">
      <div class="section-content">
        <el-table
          :data="loadDetailsList"
          border
          stripe
          style="width: 100%"
          max-height="400"
        >
          <el-table-column prop="day" label="日期" width="120" fixed="left">
          </el-table-column>
          <el-table-column
            v-for="(time, index) in timeColumns"
            :key="index"
            :label="time"
            width="80"
            align="right"
          >
            <template slot-scope="scope">
              {{ scope.row.loadList && scope.row.loadList[index] }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 考虑周末 -->
    <div class="section weekend-section">
      <div class="section-title">考虑周末</div>
      <div class="weekend-content">
        <el-radio-group
          v-model="form.considerWeekendFlag"
          size="small"
          :disabled="readonly"
          @change="handleWeekendChange"
        >
          <el-radio-button :label="true">考虑</el-radio-button>
          <el-radio-button :label="false">不考虑</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 用电负荷调整 -->
    <div class="section load-adjustment">
      <div class="section-title">用电负荷调整</div>
      <div class="section-content">
        <div class="slider-item">
          <div class="slider-label">
            <span>未来负荷增长:</span>
          </div>
          <div class="slider-wrapper">
            <el-slider
              v-model="form.futureLoadGrowthRatio"
              :min="50"
              :max="200"
              :step="1"
              :marks="loadGrowthMarks"
              :show-tooltip="true"
              :format-tooltip="formatPercentage"
              :disabled="readonly"
              @change="handleLoadGrowthChange"
            >
            </el-slider>
          </div>
        </div>
        <div class="slider-item">
          <div class="slider-label">
            <span>满充满放天数:</span>
          </div>
          <div class="slider-wrapper">
            <el-slider
              v-model="form.fullChargeFullDischargeDay"
              :min="100"
              :max="365"
              :step="1"
              :marks="chargeDischargeDaysMarks"
              :show-tooltip="true"
              :format-tooltip="formatDays"
              :disabled="readonly"
              @change="handleChargeDischargeDaysChange"
            >
            </el-slider>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { stepTwoImportApi } from '@/api/Microgrid/EnergyStoragePlanning'

export default {
  name: 'StepTwo',
  props: {
    formData: {
      type: Object,
      default: () => ({})
    },
    stepOneId: {
      type: [Number, String],
      default: null
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loadDetailsList: [], // 导入的负荷数据列表
      uploadApiFunction: stepTwoImportApi, // 上传API函数
      timeColumns: [], // 时间列（96个点，每15分钟一个）
      form: {
        considerWeekendFlag:
          this.formData.stepTwoData?.considerWeekendFlag ?? false,
        futureLoadGrowthRatio:
          this.formData.stepTwoData?.futureLoadGrowthRatio ?? 100,
        fullChargeFullDischargeDay:
          this.formData.stepTwoData?.fullChargeFullDischargeDay ?? 200
      },
      loadGrowthMarks: {
        50: '50%',
        100: '100%',
        150: '150%',
        200: '200%'
      },
      chargeDischargeDaysMarks: {
        100: '100',
        200: '200',
        300: '300',
        365: '365'
      }
    }
  },
  watch: {
    formData: {
      handler(newVal) {
        if (newVal && newVal.stepTwoData) {
          this.form.considerWeekendFlag =
            newVal.stepTwoData.considerWeekendFlag ?? false
          this.form.futureLoadGrowthRatio =
            newVal.stepTwoData.futureLoadGrowthRatio ?? 100
          this.form.fullChargeFullDischargeDay =
            newVal.stepTwoData.fullChargeFullDischargeDay ?? 200
          // 如果有导入的数据，也更新
          if (newVal.stepTwoData.loadDetailsList) {
            this.loadDetailsList = newVal.stepTwoData.loadDetailsList
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    // 生成96个时间点（每15分钟一个）
    this.generateTimeColumns()
  },
  methods: {
    // 生成96个时间点列
    generateTimeColumns() {
      const columns = []
      for (let hour = 0; hour < 24; hour++) {
        for (let minute = 0; minute < 60; minute += 15) {
          const timeStr = `${hour.toString().padStart(2, '0')}:${minute
            .toString()
            .padStart(2, '0')}`
          columns.push(timeStr)
        }
      }
      this.timeColumns = columns
    },
    // 文件解析成功回调
    handleParseSuccess(data) {
      this.loadDetailsList = data
      this.updateFormData()
    },
    // 文件上传重置回调
    handleUploadReset() {
      this.loadDetailsList = []
      this.updateFormData()
    },
    // 下载模板
    handleDownloadTemplate() {
      this.downloadUrl()
    },
    // 重置第二步数据（当第一步重新保存时调用）
    resetStepTwoData() {
      if (this.$refs.fileUpload) {
        this.$refs.fileUpload.resetUpload()
      }
      this.loadDetailsList = []
      // 重置表单数据为默认值
      this.form.considerWeekendFlag = false
      this.form.futureLoadGrowthRatio = 100
      this.form.fullChargeFullDischargeDay = 200
      this.updateFormData()
    },
    handleLoadGrowthChange(value) {
      this.updateFormData()
    },
    handleChargeDischargeDaysChange(value) {
      this.updateFormData()
    },
    handleWeekendChange(value) {
      this.updateFormData()
    },
    formatPercentage(val) {
      return `${val}%`
    },
    formatDays(val) {
      return `${val}`
    },
    // 下载文件模板
    downloadUrl() {
      const a = document.createElement('a')
      a.href = '负荷导入模板.xls'
      a.download = '负荷导入模板.xls'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    updateFormData() {
      this.$emit('update:form-data', {
        ...this.formData,
        stepTwoData: {
          considerWeekendFlag: this.form.considerWeekendFlag,
          futureLoadGrowthRatio: this.form.futureLoadGrowthRatio,
          fullChargeFullDischargeDay: this.form.fullChargeFullDischargeDay,
          loadDetailsList: this.loadDetailsList
        }
      })
    },
    // 获取第二步提交数据
    getSubmitData() {
      return {
        id: this.stepOneId ? Number(this.stepOneId) : null, // 必传，使用第一步返回的ID，转换为数字
        considerWeekendFlag: this.form.considerWeekendFlag,
        futureLoadGrowthRatio: this.form.futureLoadGrowthRatio,
        fullChargeFullDischargeDay: this.form.fullChargeFullDischargeDay,
        loadDetailsList: this.loadDetailsList
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.step-two {
  .section {
    margin-bottom: 30px;
    background-color: #fff;
    border-radius: 4px;
    padding: 20px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .section-title {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 0;
      }

      .template-download {
        font-size: 14px;
        color: #606266;

        .link-style {
          color: #3cb7e9;
          text-decoration: underline;
          cursor: pointer;
          margin-left: 5px;

          &:hover {
            color: #551a8b;
          }
        }
      }
    }

    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 20px;
    }

    .section-content {
      padding: 0;
    }
  }

  @keyframes rotating {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  // 数据表格
  .data-table-section {
    .section-content {
      overflow-x: auto;
    }
  }

  // 考虑周末
  .weekend-section {
    .weekend-content {
      display: flex;
      align-items: center;
    }
  }

  // 用电负荷调整
  .load-adjustment {
    .section-content {
      padding: 20px;
    }

    .slider-item {
      margin-bottom: 30px;

      &:last-child {
        margin-bottom: 0;
      }

      .slider-label {
        margin-bottom: 10px;
        font-weight: bold;
      }

      .slider-wrapper {
        position: relative;
        width: 100%;
        padding: 0 10px;

        ::v-deep .el-slider {
          width: 100%;

          .el-slider__marks-text {
            white-space: nowrap;
          }
        }
      }
    }
  }
}
</style>
